import { authMiddleware } from '@/lib/api';
import { queryPath, queryPostEditInfo } from '@/services/api';
import { cookies } from 'next/headers';
import Metadata from '@/lib/metadata';
import EditPostPage from '@/app/[locale]/posts/[id]/edit/edit';
import ResetPage from '@/app/[locale]/reset/reset';
import { Metadata as MetadataNext } from 'next';
import { FORBIDDEN_VALUE, getMetadata, UNAUTHORIZED_VALUE } from '@/lib/tool';
import { notFound } from 'next/navigation';
import type { IPath, IPostEditInfo } from '@/interfaces';
import EditPostH5Page from '@/app/[locale]/mobile/posts/[id]/edit/h5';
import { createTranslator } from 'next-intl';
import { getMessages } from '@/lib/dictionaries';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = createTranslator(await getMessages(locale));
  return getMetadata({ title: t('PostEditPage.editPost') });
}

export default async function Page({
  params = {},
  searchParams = {},
}: {
  params: { id?: string };
  searchParams: { v?: 'h5' };
}) {
  if (!params.id) {
    notFound();
  }

  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/posts/[id]/edit',
      },
    });
    const req2 = queryPostEditInfo({
      baseURL: process.env.APP_API_SERVER,
      token,
      id: params.id,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    const path = resp1.data as IPath;
    const info = resp2.data as IPostEditInfo;
    if (!path.user) {
      return <ResetPage error={UNAUTHORIZED_VALUE} />;
    } else if (path.user.id !== info.basic.createdBy) {
      return <ResetPage error={FORBIDDEN_VALUE} />;
    }

    const metadata = new Metadata();
    metadata.set('page', ['/paths', '/posts/[id]/edit'], path);
    metadata.set('editPost', ['/forum', '/posts', params.id, '/edit'], info);
    return searchParams.v === 'h5' ? (
      <EditPostH5Page metadata={metadata.toString()} />
    ) : (
      <EditPostPage metadata={metadata.toString()} />
    );
  } catch (e) {
    return <ResetPage error={e} />;
  }
}
